/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package photohub.action;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author liqilei
 */
public abstract  class BaseAction extends HttpServlet  {

    protected static final String VIEW_LOCATION = "/WEB-INF/view/";
    protected static final String VIEW_POSTFIX = ".jsp";
    protected static final String DATE_FORMAT = "yyyy-MM-dd";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doBoth(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doBoth(req, resp);
    }

    protected void doBoth(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String viewName = execute(req, resp);
        if (viewName != null) {
            RequestDispatcher dispatcher = req.getRequestDispatcher(VIEW_LOCATION + viewName + VIEW_POSTFIX);
            dispatcher.forward(req, resp);
        }
    }

    protected String getString(HttpServletRequest req, String name) {
        String stringValue = req.getParameter(name);
        if (stringValue == null) {
            stringValue = "";
        }
        return stringValue;
    }

    protected int getInt(HttpServletRequest req, String name) {
        String stringValue = req.getParameter(name);
        int intValue = 0;
        try {
            intValue = Integer.parseInt(stringValue);
        } catch (NumberFormatException e) {
            //format error
        }
        return intValue;
    }

    protected Date getDate(HttpServletRequest req, String name) {
        String stringValue = req.getParameter(name);
        DateFormat format = new SimpleDateFormat(DATE_FORMAT);
        Date dateValue = new Date();
        try {
            dateValue = format.parse(stringValue);
        } catch (ParseException e) {
            //format error
        }
        return dateValue;
    }

    protected void setDate(HttpServletRequest req, String name, Date value) {
        DateFormat format = new SimpleDateFormat(DATE_FORMAT);
        String stringValue = format.format(value);
        req.setAttribute(name, stringValue);
    }

    protected abstract String execute(HttpServletRequest req, HttpServletResponse resp) throws IOException;
}
